package com.xuecheng.content.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.xuecheng.commons.constants.CourseConstants;
import com.xuecheng.commons.enums.ErrorCode;
import com.xuecheng.commons.model.vo.ResponseResult;
import com.xuecheng.commons.model.vo.TeachplanDto;
import com.xuecheng.commons.model.vo.TeachplanVo;
import com.xuecheng.commons.utils.BeanHelper;
import com.xuecheng.content.domain.CourseBase;
import com.xuecheng.content.domain.Teachplan;
import com.xuecheng.content.mappers.TeachplanMapper;
import com.xuecheng.content.service.CourseBaseService;
import com.xuecheng.content.service.TeachplanService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xuecheng.web.exception.BusinessException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 课程计划 服务实现类
 * </p>
 *
 * @author itheima
 * @since 2022-07-16
 */
@Service
public class TeachplanServiceImpl extends ServiceImpl<TeachplanMapper, Teachplan> implements TeachplanService {

    @Autowired
    TeachplanMapper teachplanMapper;
    @Override
    public ResponseResult treeNodes(Long courseId) {
        //根据课程id,一次性查询所有的课程计划数据
        List<TeachplanVo> teachplanVos = teachplanMapper.treeNodes(courseId);
        //提取出1级大纲，返回值
        TeachplanVo parent = teachplanVos.stream()
                .filter(vo -> vo.getGrade() == 1)
                .findFirst()
                .get();
        //提取2级大纲，设置到1级中
        List<TeachplanVo> twos = teachplanVos.stream()
                .filter(vo -> vo.getGrade() == 2)
                .collect(Collectors.toList());
        parent.setTeachPlanTreeNodes(twos);
        //循环所有的2级大纲，查询每个二级大纲下的三级
        for (TeachplanVo two : twos) {
            List<TeachplanVo> threes = teachplanVos.stream()
                    .filter(vo -> vo.getGrade() == 3 && vo.getParentid().equals(two.getId()))
                    .collect(Collectors.toList());
            two.setTeachPlanTreeNodes(threes);
        }
        return ResponseResult.okResult(parent);
    }

    @Autowired
    CourseBaseService courseBaseService;
    @Override
    public ResponseResult saveOrUpdatePlan(TeachplanDto dto) {
        //判断课程这状态
        //获取课程id
        Long courseId = dto.getCourseId();
        //查询课程
        CourseBase courseBase = courseBaseService.getById(courseId);
        //判断课程状态
        if(! courseBase.getAuditStatus().equals(CourseConstants.AUDIT_DISPAST_STATUS)
                && ! courseBase.getAuditStatus().equals(CourseConstants.AUDIT_UNPAST_STATUS)) {
            throw new BusinessException(ErrorCode.UPDATEEERROR);
        }
        //处理Parentid为空的情况(保存2级大纲),
        if (dto.getParentid()==null) {
            //保存2级课程计划,查询1级课程计划
            LambdaQueryWrapper<Teachplan> qw=new LambdaQueryWrapper<>();
            qw.eq(Teachplan::getGrade,CourseConstants.FIRST_LEVEL);
            qw.eq(Teachplan::getCourseId,courseId);
            Teachplan teachplan = this.getOne(qw);
            //判断parent是否为空
            dto.setParentid(teachplan.getId());
        }
        //将dto转化成Java实体类
        Teachplan teachplan = BeanHelper.copyProperties(dto, Teachplan.class);
        //判断保存的课程计划的ID
        boolean flag=false;
        if(teachplan.getId() == null) {
            //ID不存在，保存
            //如果是第三级计划，更新课程表的plan_num字段（作业）
            if (teachplan.getGrade()==3) {
                courseBase.setPlanNum(courseBase.getPlanNum() + 1);
                courseBaseService.updateById(courseBase);
            }
            flag = this.save(teachplan);
        }else {
            //ID存在，更新
            flag = this.updateById(teachplan);
        }
        if(!flag) {
            throw new BusinessException(ErrorCode.ERROR);
        }
        return ResponseResult.okResult();
    }

    @Override
    public ResponseResult delete(Long id) {
        //查询 课程计划
        Teachplan teachplan = this.getById(id);
        CourseBase courseBase = courseBaseService.getById(teachplan.getCourseId());
        Integer grade = teachplan.getGrade();
        boolean b=false;
        if (grade==3){
            courseBase.setPlanNum(courseBase.getPlanNum()-1);
            courseBaseService.updateById(courseBase);
        }
        b=this.removeById(teachplan);
        if (!b){
            throw new BusinessException(ErrorCode.PARAMSERROR);
        }
        return ResponseResult.okResult(null);
    }
}
